package redis

import (
	"eight-dimensional-mall/goods_srv/goods"
	"eight-dimensional-mall/goods_srv/model/mysql"
	"strconv"
)

func AddCart(userId, goodsId, num int, good mysql.Goods) error {
	key := "cart:user_id" + strconv.Itoa(userId) + ":goods_id_" + strconv.Itoa(int(good.ID))
	return RedisClient.HMSet(key, "goods_id", goodsId, "goods_title", good.GoodsTitle, "goods_price", good.GoodsPrice, "num", num, "goods_img", good.GoodsImg).Err()
}

func CartList(userId int) (CartList []*goods.ItemList, err error) {
	key := "cart:user_id" + strconv.Itoa(userId) + ":goods_id_*"
	keys, _ := RedisClient.Keys(key).Result()
	for _, key = range keys {
		result, _ := RedisClient.HGetAll(key).Result()
		goodsId, _ := strconv.Atoi(result["goods_id"])
		num, _ := strconv.Atoi(result["num"])
		goodsPrice, _ := strconv.ParseFloat(result["goods_price"], 64)

		CartList = append(CartList, &goods.ItemList{
			GoodsTitle: result["goods_title"],
			GoodsPrice: float32(goodsPrice),
			Num:        int64(num),
			GoodsImg:   result["goods_img"],
			GoodsId:    int64(goodsId),
		})
	}
	return
}
